package com.zeros.mysplashtwo.view.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.zeros.mysplashtwo.MainActivity;
import com.zeros.mysplashtwo.MyApplication;
import com.zeros.mysplashtwo.R;
import com.zeros.mysplashtwo.base.BaseActivity;
import com.zeros.mysplashtwo.bean.LoginCheckBean;
import com.zeros.mysplashtwo.presenter.LauncherPresenterImpl;
import com.zeros.mysplashtwo.utils.Constants;
import com.zeros.mysplashtwo.utils.NetCheckUtilTwo;
import com.zeros.mysplashtwo.utils.SPUtilsTwo;
import com.zeros.mysplashtwo.utils.ZlogUtilTwo;
import com.zeros.mysplashtwo.view.contract.LauncherContract;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 引导页
 */
public class LauncherActivity extends BaseActivity implements LauncherContract.View {

    @BindView(R.id.tv_second)
    TextView tvSecond;              //秒数
    @BindView(R.id.layout_skip)
    LinearLayout layoutSkip;        //跳过按钮
    @BindView(R.id.iv_advertising)
    ImageView ivAdvertising;        //广告，点击可以跳转

    private int timeCount = 0;
    private boolean continueCount = true;
    private int initTimeCount;
    private Bitmap bitmap;

    private LauncherPresenterImpl launcherPImpl;        //presenter(广告)逻辑处理类
    private LoginCheckBean loginCheckBean;

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            ZlogUtilTwo.e(String.valueOf(msg));
            tvSecond.setText(countNum() + "");
            if (continueCount) {
                handler.sendMessageDelayed(handler.obtainMessage(-1), 1000);
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_launcher);
        ButterKnife.bind(this);
        launcherPImpl = new LauncherPresenterImpl();
        launcherPImpl.attachView(this);   //绑定view

        initTimeCount = 6;
        loginCheckBean = new LoginCheckBean();
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        if (NetCheckUtilTwo.isConnected(this)) {
            launcherPImpl.getLoginCheck();
        }
        layoutSkip.setVisibility(View.GONE);
        handler.sendMessageDelayed(handler.obtainMessage(-1), 1000);
    }


    /**
     * 数秒
     */
    private int countNum() {
        timeCount++;
        initTimeCount--;
//        tvSecond.setText(String.valueOf(initTimeCount));
//        ZlogUtilTwo.e(String.valueOf(initTimeCount));

        if (timeCount == 3) {               //数秒，超过3秒后如果没有网络，则进入下一个页面
            if (!NetCheckUtilTwo.isConnected(this)) {
                continueCount = false;
                toNextActivity();
//                finish();
            }
            ZlogUtilTwo.e(String.valueOf(loginCheckBean.isPlayAd()));
            if (!loginCheckBean.isPlayAd()) {   //如果服务端不允许播放广告，则直接进入下一个页面
                continueCount = false;
                toNextActivity();
                finish();
            } else {        //如果播放，则获取本地的图片
                ivAdvertising.setVisibility(View.VISIBLE);
                layoutSkip.setVisibility(View.VISIBLE);
            }
        }
        if (timeCount == 6) {
            continueCount = false;
            toNextActivity();
        }
//        return timeCount;
        return initTimeCount;
    }

    @OnClick({R.id.iv_advertising, R.id.layout_skip})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_advertising:           // LAUNCHURL_KEY/ADPICURL_KEY
                String url = (String) SPUtilsTwo.get(this, Constants.LAUNCHURL_KEY, "null");
                ZlogUtilTwo.e(url);
                if (!url.equals("null")) {
                    continueCount = false;
                    Intent intent = new Intent(this, WebViewActivity.class);
                    intent.putExtra("title", "震惊，程序员竟然如此写代码，真相竟然是这个...");
                    intent.putExtra("url", url);
                    intent.putExtra("from", "advertising");
                    startActivity(intent);
                    finish();
                }
                break;
            case R.id.layout_skip:
//                此处点击跳过时，偌在1s时则读秒也会在跳一次，导致有两个界面
                // 我在清单模式中设置了singleTop模式
                continueCount = false;
                toNextActivity();
                finish();
                break;
        }
    }


    //根据是否保存有 token 判断去登录界面还是主界面
    private void toNextActivity() {
        synchronized (this) {
            ZlogUtilTwo.e("到下一个界面");
            Intent intent = null;
            String token = (String) SPUtilsTwo.get(this, Constants.TOKEN_KEY, "");
            if (TextUtils.isEmpty(token)) {
                intent = new Intent(this, LoginActivity.class);
            } else {
                intent = new Intent(this, MainActivity.class);
                MyApplication.setToken(token);
            }
            startActivity(intent);
            finish();
        }
    }


    /*******************----LauncherContract.View接口-----****************/
    @Override
    public void setLauncherTime(int count) {
        initTimeCount = count + 3;
        tvSecond.setText(String.valueOf(initTimeCount));
    }

    @Override
    public void setLoginCheckBean(LoginCheckBean loginCheckBean) {
        this.loginCheckBean = loginCheckBean;
    }

    @Override
    public void setLauncherImg(Bitmap bitmap) {
        if (bitmap != null) {
            ivAdvertising.setImageBitmap(bitmap);

            //加强用户体验，如果是获取到的bitmap为null，则直接跳过
        } else {
            continueCount = false;
            toNextActivity();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //进行bitmap回收
        if (bitmap != null) {
            bitmap.recycle();
        }
        launcherPImpl.detachView();
    }

}
